package com.rzt.cft.api.controller.cms;


import com.rzt.cft.api.controller.BaseController;
import com.rzt.cft.api.fiter.CustomAuthorize;
import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.dto.ResponseData;
import com.rzt.cft.entity.cms.CmsResource;
import com.rzt.cft.exception.CustomException;
import com.rzt.cft.service.cms.ICmsResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * <p>
 * 基础-资源信息 前端控制器
 * </p>
 *
 * @author zhongzhong
 * @since 2020-01-11
 */
@RestController
@RequestMapping("/v1/api/cms-resource/")
@Slf4j
@Api(tags = "文件上传接口")
public class CmsResourceController extends BaseController {

    @Autowired
    private ICmsResourceService cmsResourceService;

    @PostMapping("upload")
    @ApiOperation("文件上传")
    @CustomAuthorize(skip = true)
    public ResponseData<String> upload(@RequestParam("file") MultipartFile file) throws Exception{
        if(file.isEmpty()){
            return fail(ServiceStatus.THE_FILE_IS_EMPTY);
        }
        String fileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
        if(fileName.contains("..")){
            return fail(ServiceStatus.FILE_PATH_ERROR);
        }
        String url = cmsResourceService.uploadFile(file);
        if (StringUtils.isNotBlank(url)) {
            return success(url);
        }
        return fail();
    }

    @GetMapping("getResource/{id}")
    @ApiOperation("文件读取图片")
    @CustomAuthorize(skip = true)
    public void getResource(@PathVariable String id, HttpServletResponse response) throws Exception{
        if (StringUtils.isBlank(id)) {
            throw new CustomException(ServiceStatus.PARAM_EXCEPTION);
        }
        CmsResource cmsResource = cmsResourceService.getById(id);
        if (Objects.isNull(cmsResource)) {
            throw new CustomException(ServiceStatus.PARAM_EXCEPTION);
        }
        String path = cmsResource.getPath() + cmsResource.getFileKey();
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);

        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
    }
}
